//
//  CJExten+UserDefaults.swift
//  CJPack
//
//  Created by 陈警卫 on 2023-09-28.
//

import Foundation

public extension UserDefaults {
    
    /// 存值
    @objc static func cj_set(key: String, value: Any) {
        self.standard.set(value, forKey: key)
        self.standard.synchronize()
    }
    
    /// 取值
    @objc static func cj_value(key: String) -> Any? {
        self.standard.value(forKey: key)
    }
    
    /// 移除值
    @objc static func cj_remove(key: String) {
        self.standard.removeObject(forKey: key)
    }
    
    /// 移除所有值
    @objc static func cj_removeAll() {
        if let bundleId = Bundle.main.bundleIdentifier {
            self.standard.removePersistentDomain(forName: bundleId)
        }
    }
}

public extension UserDefaults {
    
    /// 存模型
    static func cj_setCodable<T: Codable>(object: T, key: String) {
        guard let encoded = try? JSONEncoder().encode(object) else { return }
        self.standard.set(encoded, forKey: key)
        self.standard.synchronize()
    }
    
    /// 取模型
    static func cj_getCodable<T : Codable>(type: T.Type, key: String) -> T? {
        guard let data = self.standard.data(forKey: key) else { return nil }
        guard let model = try? JSONDecoder().decode(type, from: data) else { return nil }
        return model
    }
}
